package ext.tianma.masschange.datautility;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import wt.part.WTPart;
import wt.part.WTPartUsageLink;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.util.WTProperties;

import com.ptc.core.components.descriptor.ModelContext;
import com.ptc.core.components.factory.AbstractDataUtility;
import com.ptc.core.components.rendering.guicomponents.TextBox;

import ext.tianma.masschange.util.MassChangeUtil;

public class MassChangeQuantityDataUtility extends AbstractDataUtility {
	
	private static String RESOURCE = "ext.tianma.masschange.resource.MassChangeResource";
	private static String CLASSNAME="";
	private static boolean VERBOSE = false;
	private static WTProperties wtProperties;
	private static Locale locale = null;

	static {

		try {
			CLASSNAME= MassChangeQuantityDataUtility.class.getName();
			wtProperties = WTProperties.getLocalProperties();
			locale = SessionHelper.manager.getLocale();
			VERBOSE = wtProperties.getProperty("ext.tianma.masschange.datautility.verbose", false);
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}catch (Throwable throwable) {
			throw new ExceptionInInitializerError(throwable);
		}
	}
	public MassChangeQuantityDataUtility() {

	}
	  /**
	 *输出调试信息
	 */
	private static void outDebugInfo(String info) {
		if(VERBOSE)
			System.out.println(CLASSNAME+"......"+info);
	}	

	@Override
	public Object getDataValue(String component_id, Object obj, ModelContext mc) throws WTException {
		Double quantity = 1.0;
		HttpServletRequest request = mc.getNmCommandBean().getRequest();
		Cookie[] cookies = request.getCookies();
		String QUANTITY="";		
		for (int i = 0; i < cookies.length; i++) {
			Cookie c = cookies[i];
			//System.out.println(c.getName()+"="+c.getValue());
			if(c.getName().equalsIgnoreCase("QUANTITY")) {
				QUANTITY = c.getValue().trim();
				break;
			}			
		}
		
		TextBox gui =new TextBox();
		
		//如果QUANTITY不为空,则直接返回该值
		WTPart part = null;
		if(obj instanceof WTPartUsageLink) {
			WTPartUsageLink link = (WTPartUsageLink)obj;
			quantity = link.getQuantity().getAmount();	
			part = link.getUsedBy();
		} else if(obj instanceof WTPart) {
			part = (WTPart)obj;
		}
		String name = part.getName();	
		if(QUANTITY!="" && !(MassChangeUtil.hasCA(part, mc)||MassChangeUtil.equalState(part, "UNDERREVIEW")||MassChangeUtil.equalState(part, "OBSOLESCENCE"))) {
			quantity =  Double.parseDouble(QUANTITY);
		} else if(MassChangeUtil.hasCA(part, mc)||MassChangeUtil.equalState(part, "UNDERREVIEW")||MassChangeUtil.equalState(part, "OBSOLESCENCE")){
			return quantity;
		} 
		String quantityStr = quantity.toString();
		//去除小数点和0
		String quantitySubStr = MassChangeUtil.subZeroAndDot(quantityStr);
		//gui.setLabel(quantityStr);	
		gui.setName(quantitySubStr);
		gui.setValue(quantitySubStr);		
		gui.setEditable(true);
		return gui;
	}
}
